import Request from './index'
import type { RequestConfig } from './types'
import {getConfig} from './serviceConfig'
import  {apiMapper}  from './mapping'
const apiMap = new Map(Object.entries(apiMapper))
interface MyRequestConfig<T> extends RequestConfig { //传入的参数需要满足该限制
  body?: T,
  params?:Object,
  name?:string,
}
interface MyResponse<T> {
  code: number
  message: string
  data: T
}
const request = new Request({ //默认参数
  baseURL: '',
  timeout: 1000 * 60 * 5, 
})

const MyRequest = <D, T = any>(config: MyRequestConfig<D>) => {
  let _name = config.name as string;
  let _rule = /\//g;
  let type = apiMap.get(_name).type;
  let url =  apiMap.get(_name).url;
  let params = config.params as Object[]
  let body = config.body
  /* 匹配路径参数 */
  !_rule.test(_name) && (() => {
      let urlRegex = /\{(.+?)\}/g;
      let pathParam = url.match(urlRegex);
      if (pathParam && pathParam.length > 0) {
          for (let [index, item] of pathParam.entries()) {
              let p = item.replace('{', '');
              p = p.replace('}', '');
              if (params[p] == undefined) {
                  console.warn(`参数${p}未定义`);
              } else {
                url = url.replace(item, params[p]);
              }
          }
      }
  })();
  config ={
    url,
    ...getConfig(type,body,params as Object),//整理各个格式的传参
  }
  return request.request<MyResponse<T>>(config)
}
// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return request.cancelRequest(url)
}
// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest()
}
export default MyRequest
